<?php

namespace app\api\controller\v1\user;

use app\common\controller\BaseController;
use app\common\service\EasyWechatService;
use think\Cache;
use think\Controller;
use think\Db;
use think\Request;
use app\api\model\User as UserModel;
use app\api\model\Recharge as RechargeModel;
use app\api\model\UserRechargeLog as UserRechargeLogModel;
use app\api\model\UserMoneyLog as UserMoneyLogModel;

class Recharge extends BaseController
{
    protected $noNeedLogin = [''];

    /**
     * 充值页面
     */
    public function index()
    {
        $money = UserModel::getValueByField($this->userId, 'money');
        $recharges = RechargeModel::getRecharges();
        $this->success('', compact('money', 'recharges'));
    }

    /**
     * 充值
     */
    public function pay(EasyWechatService $easyWechatService)
    {
        $this->isPost();
        $recharge_id = $this->notEmpty('recharge_id');
        $recharge = RechargeModel::find($recharge_id);
        if (!$recharge) {
            $this->errorMsg(15000);
        }
        $user = UserModel::find($this->userId);
        if (!$user) {
            $this->errorMsg(9996);
        }
        $order_no = date('YmdHis').$this->userId;
        $data = [
            'user_id' => $this->userId,
            'recharge_id' => $recharge_id,
            'order_no' => $order_no,
            'recharge_money' => $recharge->recharge_money,
            'give_money' => $recharge->give_money,
            'createtime' => time(),
            'updatetime' => time()
        ];
        //缓存订单数据
        Cache::set('recharge_'.$order_no, json_encode($data), 0);

        $res = $easyWechatService->unify(
            $data['order_no'],
            $data['recharge_money'],
            $user->wxapp_openid,
            config('wechat.recharge_notify_url')
        );
        $res['out_trade_no'] = $order_no;
        $this->success('', $res);
    }

    /**
     * 主动回调
     */
    public function notify(EasyWechatService $easyWechatService)
    {
        $orderNo = $this->notEmpty('order_no');
        $userRecharge = UserRechargeLogModel::getByOrderNo($orderNo);
        if ($userRecharge) {
            $this->success();
        }
        $data = json_decode(Cache::get('recharge_'.$orderNo), true);
        if (!$data) {
            $this->errorMsg(13001);
        }
        $user = UserModel::find($data['user_id']);
        if (!$user) {
            $this->errorMsg(9996);
        }
        //查询支付订单
        $res = $easyWechatService->find($orderNo);
        $this->paySuccess($data, $user);
    }

    /**
     * 自动回调
     */
    public function paymentResult(EasyWechatService $easyWechatService)
    {
        $response = $easyWechatService->app()->handlePaidNotify(function ($res, $fail) {
            if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
                $courseOrder = CourseOrderModel::getByOrderNo($res['out_trade_no']);
                if (!$courseOrder) {
                    $data = json_decode(Cache::get('recharge_'.$res['out_trade_no']), true);
                    $user = UserModel::find($data['user_id']);
                    if ($data) {
                        $this->paySuccess($data, $user);
                    }
                }
            } else {
                return $fail('支付异常，请联系管理员');
            }
        });
        $response->send();
    }


    /**
     * 支付处理
     */
    private function paySuccess($data, $user)
    {
        Db::startTrans();
        try {
            $userRechargeLog = UserRechargeLogModel::create($data);
            $money = $userRechargeLog->recharge_money + $userRechargeLog->give_money;
            //金额变化
            UserMoneyLogModel::add($user, $money, '充值');
            //用户金额
            $user->setInc('money', $money);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        if (isset($e)) {
            $this->errorMsg(13002);
        } else {
            Cache::rm('recharge_'.$data['order_no']);
            $this->success();
        }

    }

    /**
     * 充值记录
     */
    public function log()
    {
        $log = UserRechargeLogModel::getByUserId($this->userId, $this->request->get('size'));
        $log->total() ? $this->success('', [
            'log' => $log->items(),
            'total' => $log->total()
        ]) : $this->notFoundData();
    }

}
